package com.common.weibolib;

import android.content.Context;
import android.text.Html;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.method.Touch;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

import com.common.weibolib.Utils.URLSpanNoUnderline;
import com.common.weibolib.Utils.UrlImageSpan;

/**
 * 
 * ClassName:ProTextView Function: 处理@，url ,表情等复杂文本的TextView Reason: TODO ADD
 * REASON
 * 
 * @author huangszh
 * @version
 * @since Ver 1.1
 * @Date 2013 2013-12-11 上午11:38:18
 * 
 * @see
 */
public class ProTextView extends TextView {
	boolean dontConsumeNonUrlClicks = true;
	boolean linkHit = false;

	public ProTextView(Context context) {
		super(context);
	}

	public ProTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ProTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		linkHit = false;
		// reason : the Layout that is currently being used to display the text. This can be null if the text or width has recently changes.
		// result : 导致LinkMovementMethod里面只接收到DOWN的事件，其他再也接收不到，需要特殊处理
		if (getLayout() == null && getText() instanceof Spannable) {
			LocalLinkMovementMethod.getInstance().cleanSelectSpan(this,(Spannable) getText(),event.getAction() == MotionEvent.ACTION_UP );
			linkHit = true;
		}

		boolean res = super.onTouchEvent(event);

		if (dontConsumeNonUrlClicks) {
			res = linkHit;// linkHit在LocalLinkMovementMethod方法中可能改变
		}
		return res;
	}

	@Override
	public boolean performLongClick() {
		return true;
	}

	public void setTextViewHTML(String html) {
		CharSequence sequence = Html.fromHtml(html);
		SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
		setText(strBuilder);
	}

	public static class LocalLinkMovementMethod extends LinkMovementMethod {
		static LocalLinkMovementMethod sInstance;
		private UrlImageSpan mSelectImageSpan;
		private URLSpanNoUnderline mSelectClickSpan;

		public static LocalLinkMovementMethod getInstance() {
			if (sInstance == null)
				sInstance = new LocalLinkMovementMethod();

			return sInstance;
		}

		/**
		 * 
		 * @n<b>函数名称</b>     :cleanSelectSpan
		 * @brief	清空之前选中的ClickableSpan和UrlImageSpan，清空之前是否执行ClickableSpan的click事件由外部传参决定
		 * @see
		 * @since    Ver 1.1
		 * @param  @param widget
		 * @param  @param buffer
		 * @param  @param doClick	true的话表示清空之前需要执行ClickableSpan的click事件，否则不需要
		 * @return void
		 * @<b>作者</b>          :  huangszh
		 * @<b>创建时间</b>      :  2013-12-19上午9:51:05
		 */
		public void cleanSelectSpan(TextView widget, Spannable buffer,boolean doClick) {
			if (mSelectImageSpan != null) {
				Utils.setUrlImageSpan(widget, mSelectImageSpan, buffer, false,null);
				mSelectImageSpan = null;
			}
			if(doClick && mSelectClickSpan != null){
				mSelectClickSpan.onClick(widget);
			}
			mSelectClickSpan = null;
		}

		@Override
		public boolean onTouchEvent(TextView widget, Spannable buffer,
				MotionEvent event) {
			try {
				int action = event.getAction();

				if (action == MotionEvent.ACTION_DOWN
						|| action == MotionEvent.ACTION_MOVE) {
					int x = (int) event.getX();
					int y = (int) event.getY();

					x -= widget.getTotalPaddingLeft();
					y -= widget.getTotalPaddingTop();

					x += widget.getScrollX();
					y += widget.getScrollY();

					Layout layout = widget.getLayout();
					int line = layout.getLineForVertical(y);
					int off = layout.getOffsetForHorizontal(line, x);

					// 处理@ ，url 等
					URLSpanNoUnderline[] link = buffer.getSpans(off, off,
							URLSpanNoUnderline.class);

					if (action == MotionEvent.ACTION_DOWN) {
						if (link.length != 0) {
							// 有Click,判断是否为超链接URL
							UrlImageSpan[] image = buffer.getSpans(off, off,UrlImageSpan.class);

							// 是的话,重绘按下状态的URL图片
							if (image.length != 0) {
								mSelectImageSpan = Utils.setUrlImageSpan(widget, image[0], buffer, true, null);
							}

							// 设置当前选中
							mSelectClickSpan = link[0];

							if (widget instanceof ProTextView) {
								((ProTextView) widget).linkHit = true;
							}
							return true;
						}
					} else if (action == MotionEvent.ACTION_MOVE) {
						boolean isNewLink = link.length == 0 ? false : !link[0].equals(mSelectClickSpan);
						// 如果移出之前选中的URL区域或者移到新的URL区域，
						// selectClickSpan 和 selectImageSpan置为null，UrlImageSpan恢复到原始状态
						if ((link.length == 0 && mSelectClickSpan != null)
								|| isNewLink) {
							
							cleanSelectSpan(widget, buffer, false);
						}

						// 移到其他URL区域内，清除之前的选中或者还原UrlImageSpan为普通状态,重新判断当前
						if (isNewLink) {
							mSelectClickSpan = link[0];
							UrlImageSpan[] image = buffer.getSpans(off, off,UrlImageSpan.class);
							// 是的话,重绘按下状态的URL图片
							if (image.length != 0) {
								mSelectImageSpan = Utils.setUrlImageSpan(widget, image[0], buffer, true, null);
							}
						}
						if (widget instanceof ProTextView) {
							((ProTextView) widget).linkHit = true;
						}
						return true;
					}
				} else if (action == MotionEvent.ACTION_UP) {
					// 执行UP
					cleanSelectSpan(widget,buffer,true);

					if (widget instanceof ProTextView) {
						((ProTextView) widget).linkHit = true;
					}
					return true;
				} else {
					// 接收其它事件(Cancel)的时候状态还原，选中置空，执行父级操作。
					cleanSelectSpan(widget, buffer,false);
				}

				return Touch.onTouchEvent(widget, buffer, event);
			} catch (NullPointerException e) { // 捕获TextView.getTotalPaddingTop可能存在的NullPointerException
				return false;
			}

		}

	}

}